package com.mapfinal.server.local;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.jfinal.kit.StrKit;
import com.lambkit.Lambkit;
import com.lambkit.core.aop.AopKit;
import com.lambkit.core.config.ConfigManager;
import com.mapfinal.server.ServerLayer;

public class LocalServerManager {
	private static final String DATASOURCE_PREFIX = "mapfinal.local.";
	private static LocalServerManager manager;

	public static LocalServerManager me() {
		if (manager == null) {
			manager = AopKit.singleton(LocalServerManager.class);
		}
		return manager;
	}
	
		private LocalClusterServer servers;

		private LocalServerManager() {
			//service = new GeoserverService();

			LocalConfig config = Lambkit.config(LocalConfig.class, "lambkit.geoserver");
			config.setName(LocalConfig.NAME_DEFAULT);
			servers.addServer(LocalServer.create(config));

			Properties prop = ConfigManager.me().getProperties();
			Set<String> serverNames = new HashSet<>();
			for (Map.Entry<Object, Object> entry : prop.entrySet()) {
				String key = entry.getKey().toString();
				if (key.startsWith(DATASOURCE_PREFIX) && entry.getValue() != null) {
					String[] keySplits = key.split("\\.");
					if (keySplits.length == 4) {
						serverNames.add(keySplits[2]);
					}
				}
			}

			for (String name : serverNames) {
				LocalConfig dsc = ConfigManager.me().get(LocalConfig.class, DATASOURCE_PREFIX + name);
				if (StrKit.isBlank(dsc.getName())) {
					dsc.setName(name);
				}
				servers.addServer(LocalServer.create(dsc));
			}
		}
		
		public List<LocalServer> getServers(String layerName) {
			return servers.getServers(layerName);
		}

		public LocalServer getBestServer(String layerName) {
			return servers.getBestServer(layerName);
		}
		
		public LocalServer getServer(String name) {
			return servers.getServer(name);
		}

		public LocalServer getDefaultServer() {
			return servers.getDefaultServer();
		}

		public LocalServerLayer getServerLayer(String layerName) {
			ServerLayer serverLayer = servers.getServerLayer(layerName);
			return serverLayer==null ? null : (LocalServerLayer)serverLayer;
		}
}
